﻿namespace MsForgeReboot.Web {
    #region Usings

    using System;
    using System.Linq;
    using System.Web.Security;

    using MsForgeReboot.Framework.Entities;
    using MsForgeReboot.Services;

    using WebMatrix.WebData;

    #endregion

    public static class SecurityConfig {
        #region Public Methods and Operators

        public static void InitalizeAndSeedSecurity() {
            try {
                WebSecurity.InitializeDatabaseConnection(
                    "MsForgeContext", "Users", "Id", "Username", autoCreateTables: false);
                CreateDefaultSecurityGroups();
            }
            catch (Exception e) {
                throw new ApplicationException("Roles seed failed", e);
            }
        }

        /// <summary>
        /// Creates the default security groups.
        /// </summary>
        private static void CreateDefaultSecurityGroups() {
            var ctx = new MsForgeContext();
            // check for existence of roles and the user
            var roles = ctx.Roles.Count(r => r.Name == "Administrators" || r.Name == "Visitors");
            var admin = ctx.Users.SingleOrDefault(u => u.Username == "admin@msforge.net");
            if (roles <= 0 && admin == null) {
                ctx.Roles.Add(new Role { Name = "Administrators" });
                ctx.Roles.Add(new Role { Name = "Visitors" });
                ctx.SaveChanges();
                WebSecurity.CreateUserAndAccount(
                    "admin@msforge.net",
                    "administrator",
                    new { PublicName = "Administrator", IsValidated = true, ReceiveNotifications = true });
                Roles.AddUserToRole("admin@msforge.net", "Administrators");
            }
        }

        #endregion
    }
}